<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once(APPPATH.'libraries/excel/classes/PHPExcel.php');
/**
 * 自定义excel解析类
 */
class Mexcel{
    private $_phpexcel = null;//PHPExcel类的实例
    private $_filename = null;//excel文件路径
    public function __construct() {
        $this->_phpexcel = new PHPExcel();
    }
    /**
     * excel转数组
     * @param type $filename
     * @return array
     */
    public function excel_to_array($filename){
        $result = array();
        $this->_filename = BASEPATH.'..'.$filename;
        if($this->is_file()){
            //读取Excel文件类实例化
            $PHPReader = new PHPExcel_Reader_Excel5();
            if(!$PHPReader->canRead($this->_filename)){
                $PHPReader = new PHPExcel_Reader_Excel2007();
                if(!$PHPReader->canRead($this->_filename)){
                    $result['status'] = 0;
                    $result['error'] = '未知版本的Excel';
                    return $result;
                }
            }
            //读取Excel文件
            $PHPExcel = $PHPReader->load($this->_filename);
            //获得第一张工作表
            $sheet = $PHPExcel->getSheet(0);
            //获取总行数
            $rows = $sheet->getHighestRow();
            //获取总列数
            $columns = $sheet->getHighestColumn(); 
            $columns = PHPExcel_Cell::columnIndexFromString($columns);//字母列转换为数字列 如:AA变为27
            $data = array();
            for($row = 2;$row <= $rows;$row ++){//行数是以第1行开始
                $temp = array();
                $key = 0;
                for($column = 0;$column < $columns;$column ++){//数是以第0列开始
                    $cell = $sheet->getCellByColumnAndRow($column, $row);
                    $value = $cell->getValue();
                    $temp[$key] = $value;
                    $key++;
                }
                if($temp[0]){
                    $data[] = $temp;
                }
            }
            //释放工作表对象
            unset($sheet);
            //释放读取Excel文件对象
            unset($PHPReader);
            //释放Excel文件对象
            unset($PHPExcel);
            //循环读取每个单元格的数据 
            $result['status'] = 1;
            $result['error'] = '';
            $result['data'] = $data;
            
        }else{
            $result['status'] = 0;
            $result['error'] = '文件不存在或格式错误';
        }     
        return $result;
    }
    
    private function is_file(){
        if($this->_filename){
            if(file_exists($this->_filename)){
                if(strpos($this->_filename, '.xls')){
                    return true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
}